package com.tbit.uqbike.client.remote.paypal;

import com.paypal.http.HttpResponse;
import com.paypal.http.exceptions.SerializeException;
import com.paypal.http.serializer.Json;
import com.paypal.orders.*;
import com.paypal.payments.CapturesGetRequest;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;

import java.io.IOException;

/**
 * @Author: chen
 * @Description: paypal扣款
 * @Date: 创建于 17:46 2021/4/21
 */
@Slf4j
public class CaptureOrder extends PayPalClient {


    private String clientId = "AfQGD3ym878GHQVA_xBPiXPNTNP_54C-IGhTgw193wd7t3nNKd6f9ekVvvvAEjtbEYcnmQYZD5ER4y-k";
    private String clientSecret = "EAmRYJfb6fuQ0UCFjKIuJipcnG2A5oq4-PKlN4TLYb8Jp4C5P5c2EbM7TyoMX3f5FLX28Bn5sHBcBdLF";
    private String mode = "sandbox";

    public static void main(String[] args) {
        try {
            CaptureOrder captureOrder = new CaptureOrder();
            new CaptureOrder().captureOrder(captureOrder.mode, captureOrder.clientId, captureOrder.clientSecret, "09X79473YV874873H");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public OrderRequest buildRequestBody() {
        return new OrderRequest();
    }

    /**
     * 用户授权支付成功，进行扣款操作
     */
    public Capture captureOrder(String mode, String clientId, String clientSecret, String orderId) throws IOException {
        OrdersCaptureRequest request = new OrdersCaptureRequest(orderId);
        request.requestBody(new OrderRequest());
        PayPalClient payPalClient = new PayPalClient();
        HttpResponse<Order> response = null;
        try {
            response = payPalClient.client(mode, clientId, clientSecret).execute(request);
        } catch (IOException e1) {
            try {
                log.error("第1次调用paypal扣款失败");
                response = payPalClient.client(mode, clientId, clientSecret).execute(request);
            } catch (Exception e) {
                try {
                    log.error("第2次调用paypal扣款失败");
                    response = payPalClient.client(mode, clientId, clientSecret).execute(request);
                } catch (Exception e2) {
                    log.error("第3次调用paypal扣款失败，失败原因 {}", e2);
                }
            }
        }
        log.info(String.format("Status Code = %s, Status = %s, OrderID = %s", response.statusCode(), response.result().status(), response.result().id()));
        for (LinkDescription link : response.result().links()) {
            log.info(String.format("Links-%s: %s    \tCall Type: %s", link.rel(), link.href(), link.method()));
        }
        for (PurchaseUnit purchaseUnit : response.result().purchaseUnits()) {
            for (Capture capture : purchaseUnit.payments().captures()) {
                log.info("Capture id: {}" + capture.id());
                log.info("status: {}" + capture.status());
                log.info("invoice_id: {}" + capture.invoiceId());
                if ("COMPLETED".equals(capture.status())) {
                    //进行数据库操作，修改订单状态为已支付成功，尽快发货（配合回调和CapturesGet查询确定成功）
                    log.info("支付成功,状态为=COMPLETED");
                }
                if ("PENDING".equals(capture.status())) {
                    log.info("status_details: {}" + capture.captureStatusDetails().reason());
                    String reason = "PENDING";
                    if (capture.captureStatusDetails() != null && capture.captureStatusDetails().reason() != null) {
                        reason = capture.captureStatusDetails().reason();
                    }
                    //进行数据库操作，修改订单状态为已支付成功，但触发了人工审核，请审核通过后再发货（配合回调和CapturesGet查询确定成功）
                    log.info("支付成功,状态为=PENDING : {}" + reason);
                }
                return capture;
            }
        }
        Payer buyer = response.result().payer();
        log.info("Buyer Email Address: {}" + buyer.email());
        //log.info("Buyer Name: {} {}", buyer.name().givenName(), buyer.name().surname());
        String json = new JSONObject(new Json().serialize(response.result())).toString(4);
        log.info("captureOrder response body: {}" + json);
        // return response;
        return null;
    }

    /**
     * 查询订单是否支付
     *
     * @param mode
     * @param clientId
     * @param clientSecret
     * @param captureId
     */
    public Boolean capturesGet(String mode, String clientId, String clientSecret, String captureId) {
        CapturesGetRequest request = new CapturesGetRequest(captureId);

        HttpResponse<com.paypal.payments.Capture> response = null;
        try {
            response = client(mode, clientId, clientSecret).execute(request);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        System.out.println("Status Code: " + response.statusCode());
        System.out.println("Status: " + response.result().status());
        if ("COMPLETED".equalsIgnoreCase(response.result().status())) {
            return true;
        }
        try {
            System.out.println(new JSONObject(new Json().serialize(response.result())).toString(4));
        } catch (SerializeException e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

}
